#region Using

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;

using Gizmox.WebGUI.Common;
using Gizmox.WebGUI.Forms;
using System.Collections;
using Gizmox.WebGUI.Common.Resources;
using PLACEHR.Web.Categories.Management.Forms;
using PLACEHR.Web.Utilities;

#endregion

namespace PLACEHR.Web.Categories.Management.Controls
{
    public partial class EmployeeListControl : UserControl, IHostedApplication
    {
        public EmployeeListControl()
        {
            InitializeComponent();
            InitializeData();
            Retrieve();
        }

        #region IHostedApplication

        public void InitializeApplication()
        {
        }

        public HostedToolBarElement[] GetToolBarElements()
        {
            ArrayList objElements = new ArrayList();
            objElements.Add(new HostedToolBarButton(LanLayer.GetTrans(20), LanLayer.GetTrans(20), new IconResourceHandle("Outlook.NewItem.gif"), "Retrieve"));
            objElements.Add(new HostedToolBarSeperator());
            objElements.Add(new HostedToolBarButton(LanLayer.GetTrans(21), LanLayer.GetTrans(21), new IconResourceHandle("CRM.ico_16_5006.gif"), "OpenSelected"));
            objElements.Add(new HostedToolBarSeperator());
            objElements.Add(new HostedToolBarButton(LanLayer.GetTrans(22), LanLayer.GetTrans(22), new IconResourceHandle("CRM.ico_16_1070.gif"), "Add"));
            objElements.Add(new HostedToolBarSeperator());
            objElements.Add(new HostedToolBarButton(LanLayer.GetTrans(23), LanLayer.GetTrans(23), new IconResourceHandle("CRM.ico_16_5010.gif"), "DeleteSelected"));

            return (HostedToolBarElement[])objElements.ToArray(typeof(HostedToolBarElement));
        }

        public void OnToolBarButtonClick(HostedToolBarButton objButton, EventArgs objEvent)
        {
            string strAction = (string)objButton.Tag;
            switch (strAction)
            {
                case "Retrieve":
                    Retrieve();
                    break;
                case "OpenSelected":
                    OpenDetailForm();
                    break;
                case "Add":
                    AddDetailForm();
                    break;
                case "DeleteSelected":
                    if (lvwData.CheckedItems.Count > 0)
                    {
                        MessageBox.Show("Please make sure you want to delete selected Departments!!", "Prompt", MessageBoxButtons.YesNo, MessageBoxIcon.Warning,
                                        (obj, arg) =>
                                        {
                                            if (((MessageBoxWindow)obj).DialogResult == DialogResult.Yes)
                                            {
                                                DeleteSelected();
                                                InitializeData();
                                            }
                                        });
                    }
                    else
                    {
                        MessageBox.Show("Please select which catagory you want to delete!!");
                    }
                    break;
            }
        }

        #endregion

        #region Method

        private void DeleteSelected()
        {
            foreach (ListViewItem lvwItem in lvwData.CheckedItems)
            {
                Department c = lvwItem.Tag as Department;
                c.IsDeleted = true;
                lvwData.Items.Remove(lvwItem);
                //DataRow item = lvwItem.Tag as DataRow;
                //SqlHelper.ExecuteNonQuery(Global.ConnectionString, CommandType.Text, string.Format("delete from [Catagory] where id = {0}", item["ID"].ToString()));
            }

            Global.Context.SaveChanges();
        }

        private void Retrieve()
        {
            List<Employee> employeeList = Global.Context.Employees.Where(p => !p.IsDeleted && p.RoleID < 4).ToList();

            if (!string.IsNullOrWhiteSpace(cbbEmployeeStatus.Text))
            {
                employeeList = employeeList.Where(o => o.StatusCode == cbbEmployeeStatus.Text).ToList();
            }

            if (!string.IsNullOrWhiteSpace(cbxOffice.Text))
            {
                string officeCode = cbxOffice.SelectedValue.ToString();
                employeeList = employeeList.Where(p => p.OfficeDepartment_lnk.Select(o => o.OfficeCode).FirstOrDefault() == officeCode).ToList();
            }

            if (!string.IsNullOrWhiteSpace(cbxDepartment.Text))
            {
                employeeList = employeeList.Where(p => p.OfficeDepartment_lnk != null
                    && p.OfficeDepartment_lnk.Any(k => string.Equals(cbxDepartment.SelectedValue.ToString(), k.DepartmentCode, StringComparison.OrdinalIgnoreCase))).ToList();
            }

            if (!string.IsNullOrEmpty(tbxUserName.Text))
            {
                employeeList = employeeList.Where(p => !string.IsNullOrWhiteSpace(p.ChineseName)
                    && (p.ChineseName.ToLower().Contains(tbxUserName.Text.Trim().ToLower()) || p.EnglishName.ToLower().Contains(tbxUserName.Text.Trim().ToLower()))).ToList();
            }

            //if (!string.IsNullOrEmpty(tbxEnglishName.Text))
            //{
            //    employeeList = employeeList.Where(p => !string.IsNullOrWhiteSpace(p.EnglishName) && p.EnglishName.ToLower().Contains(tbxEnglishName.Text.Trim().ToLower())).ToList();
            //}

            this.BindDataToListView(employeeList);
        }

        private void OpenDetailForm()
        {
            if (lvwData.SelectedItem != null)
            {
                Employee item = lvwData.SelectedItem.Tag as Employee;
                EmployeeForm form = new EmployeeForm();
                form.currItem = item;
                form.FormClosed += new Gizmox.WebGUI.Forms.Form.FormClosedEventHandler(form_FormClosed);
                form.ShowDialog();
            }
        }

        void form_FormClosed(object sender, FormClosedEventArgs e)
        {
            EmployeeForm form = sender as EmployeeForm;
            if (form.DialogResult == DialogResult.OK)
            {
                Retrieve();
            }
        }

        private void AddDetailForm()
        {
            EmployeeForm form = new EmployeeForm();
            form.FormClosed += new Gizmox.WebGUI.Forms.Form.FormClosedEventHandler(form_FormClosed);
            form.ShowDialog();
        }

        private void InitializeData()
        {
            lblDepartment.Text = LanLayer.GetTrans(177) + ":";
            lblName.Text = LanLayer.GetTrans(178) + ":";
            lblOffice.Text = LanLayer.GetTrans(176) + ":";
            lblEmployeeStatus.Text = LanLayer.GetTrans(192) + ":";

            colChineseName.Text = LanLayer.GetTrans(84);
            colDepartment.Text = LanLayer.GetTrans(177);
            colEmployeeID.Text = LanLayer.GetTrans(179);
            colEnglishName.Text = LanLayer.GetTrans(85);
            colGender.Text = LanLayer.GetTrans(95);
            colOffice.Text = LanLayer.GetTrans(176);
            colFinalBalance.Text = LanLayer.GetTrans(194);



            if (Global.CurrentUser.RoleID == 2 || Global.CurrentUser.RoleID == 3)
            {
                var office = Global.CurrentUser.OfficeDepartment_lnk.FirstOrDefault().Office;
                List<DictionaryEntry> itemList = new List<DictionaryEntry>();
                itemList.Add(new DictionaryEntry(office.OfficeCode, LanLayer.GetTrans(office.ContentId.Value)));
                cbxOffice.DataSource = itemList;
                cbxOffice.DisplayMember = "value";
                cbxOffice.ValueMember = "key";
            }
            else
            {
                cbxOffice.DataSource = Utility.GetOfficeList();
                cbxOffice.DisplayMember = "value";
                cbxOffice.ValueMember = "key";
            }

            cbxDepartment.DataSource = Utility.GetDeptList();
            cbxDepartment.DisplayMember = "value";
            cbxDepartment.ValueMember = "key";

            cbbEmployeeStatus.SelectedIndex = 0;
            
        }

        private void BindDataToListView(List<Employee> employeeList)
        {
            lvwData.Items.Clear();
            lvwData.BeginUpdate();
            int No = 1;
            foreach (var item in employeeList)
            {
                ListViewItem lvwItem = new ListViewItem("");
                lvwItem.SubItems.AddRange(new string[8]);

                lvwItem.SubItems[0].Text = (No++).ToString();
                lvwItem.SubItems[1].Text = item.EmployeeID.ToString();
                lvwItem.SubItems[2].Text = item.EnglishName;
                lvwItem.SubItems[3].Text = item.ChineseName;
                lvwItem.SubItems[4].Text = item.Gender;

                string office = string.Empty;
                string depart = string.Empty;
                if (item.OfficeDepartment_lnk != null && item.OfficeDepartment_lnk.Count > 0)
                {
                    foreach (var d in item.OfficeDepartment_lnk)
                    {
                        office = string.Format("{0}{1},", office, d.Office.OfficeName);
                        depart = string.Format("{0}{1},", depart, d.Department.DepartmentName);
                    }
                }

                lvwItem.SubItems[5].Text = office.Trim(new char[] { ',' });
                lvwItem.SubItems[6].Text = depart.Trim(new char[] { ',' });

                decimal finalHours = 0;
                var vacationbase = Global.Context.VacationBases.Where(o => o.Employee.EmployeeID == item.EmployeeID && o.IsDeleted == false && o.IsCurrent && o.VacationTypeCode == "ANN").FirstOrDefault();
                if (vacationbase != null)
                {
                    finalHours = vacationbase.FinalHours.HasValue ? vacationbase.FinalHours.Value : 0;
                }

                lvwItem.SubItems[7].Text = Utility.ConvertLengthToString(finalHours);


                lvwItem.Tag = item;
                lvwData.Items.Add(lvwItem);
            }

            lvwData.EndUpdate();
        }

        #endregion

        #region Event

        private void lvwData_DoubleClick(object sender, EventArgs e)
        {
            OpenDetailForm();
        }

        #endregion

        private void queryControl1_FilterQueryClick(object sender, EventArgs e)
        {
            Retrieve();
        }

        private void queryControl1_FilterResetClick(object sender, EventArgs e)
        {
            InitializeData();
        }

    }
}